<template>
    <div id="add-edit-site-inspection">
        <el-dialog
            :title="titleCon"
            v-model="isUseDialog" 
            draggable 
            :close-on-click-modal="false" 
            width="60%" 
            :before-close="handleClose"
            :destroy-on-close="true"
            @close="clean"
        >
            <el-form :model="ruleForm" ref="ruleFormRef" size="default" label-width="80px" :rules="rules">
                <el-divider content-position="left">{{ $t('l4vGAiubhrTaPWe5vDq1o') }}</el-divider>
                <el-row :gutter="35">

                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item :label="$t('kJu7Trhi2W73OAVloSf')" prop="v_ProjectName" :label-width="formLabelWidth">
                            <el-select 
                                v-model="ruleForm.v_ProjectName" 
                                filterable 
                                class="m-2" 
                                :placeholder="$t('kJu7Trhi2W73OAVloSf')" 
                                value-key="n_Id"
                                @change="projectChange"
                            >
                                <el-option
                                    v-for="item in projectOption"
                                    :key="item.n_Id"
                                    :label="item.v_ItemProjectName"
                                    :value="item.n_Id"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>

                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item :label="$t('0lStt1He43KyEyp1ExrB')" :label-width="formLabelWidth">
                            <el-input readonly disabled v-model="n_ItemProjectId" :placeholder="$t('mUNbt0mHr7tCccPuaTVv')" clearable />
                        </el-form-item>
                    </el-col>

                    <!-- <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="测试自定义上传" :label-width="formLabelWidth">
                            <upload-file
                                fileName="自定义上传"
                                accept=".jpg,.png,.jpeg"
                                @fileArr="fileArrFun"
                            />
                        </el-form-item>
                    </el-col> -->

                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item :label="$t('g9KAsQ73ULwCiJCd4zgLm')" prop="n_OrgId" :label-width="formLabelWidth">
                            <el-tree-select
                                ref="treeRef"
                                filterable
                                v-model="ruleForm.v_TeamName"
                                :data="treeData"
                                :default-expand-all="true"
                                node-key="value"
                                :props="treeProps"
                                check-strictly
                                :render-after-expand="false"
                                @change="orgChange"
                            />
                        </el-form-item>
                    </el-col>

                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item :label="$t('mEj5wDmCZsCfxTRosWxRj')" :label-width="formLabelWidth">
                            <el-cascader 
                                v-model="ruleForm.levelIds" 
                                :options="explainOption" 
                                collapse-tags 
                                filterable 
                                :props="checkProps"
                                @change="hazardChange"
                                clearable 
                            />
                        </el-form-item>
                    </el-col>

                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item :label="$t('1rj8iDVdCaStJmgRvySfL')" prop="v_SecurityEmpName" :label-width="formLabelWidth">
                            <el-select 
                                v-model="ruleForm.v_SecurityEmpName" 
                                filterable 
                                class="m-2" 
                                :placeholder="$t('1rj8iDVdCaStJmgRvySfL')" 
                                value-key="id"
                                @change="securChange"
                            >
                                <el-option
                                    v-for="item in securOption"
                                    :key="item.id"
                                    :label="item.name"
                                    :value="item.id"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>

                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item :label="$t('uXzsqojkX5OpKyUYpdTi')" prop="v_CheckTypeName" :label-width="formLabelWidth">
                            <el-select 
                                v-model="ruleForm.v_CheckTypeName" 
                                filterable 
                                class="m-2" 
                                :placeholder="$t('uXzsqojkX5OpKyUYpdTi')" 
                                value-key="id"
                                @change="checkChange"
                            >
                                <el-option
                                    v-for="item in checkOption"
                                    :key="item.n_Id"
                                    :label="item.value"
                                    :value="item.id"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>

                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item :label="$t('yiTBq9B5WxzVUpNzLoxo')" :label-width="formLabelWidth">
                            <el-select 
                                v-model="ruleForm.v_ThenCheckTypeName" 
                                filterable 
                                class="m-2" 
                                :placeholder="$t('on7JzukuXeSipYIjWYDw')" 
                                value-key="value"
                                @change="thenChange"
                            >
                                <el-option
                                    v-for="item in thenOption"
                                    :key="item.n_Id"
                                    :label="item.value"
                                    :value="item.id"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>

                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item :label="$t('eFdfElVxdu3C5z7m3i7zk')" :label-width="formLabelWidth" prop="v_WorkContent">
                            <el-input type="textarea" v-model="ruleForm.v_WorkContent" :placeholder="$t('eFdfElVxdu3C5z7m3i7zk')" clearable />
                        </el-form-item>
                    </el-col>

                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item :label="$t('6Ux7qeGToKiSGgcThOtAh')" :label-width="formLabelWidth" prop="d_CheckDate">
                            <el-date-picker
                                v-model="ruleForm.d_CheckDate"
                                type="datetime"
                                value-format="YYYY-MM-DD HH:mm:ss"
                                :placeholder="$t('xYKtSx361Hm1x9r3giOx')"
                                popper-class="el-date-p"
                            >
                            </el-date-picker>
                        </el-form-item>
                    </el-col>

                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item :label="$t('m9q2YwDsvEhUwSsnBlmH8')" :label-width="formLabelWidth" prop="v_Weather">
                            <el-input v-model="ruleForm.v_Weather" :placeholder="$t('d_7PcGsY5sV8YsNlUoLtK')" clearable />
                        </el-form-item>
                    </el-col>

                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item :label="$t('sfwbsExMM3lGjDuN5zHf')" :label-width="formLabelWidth">
                            <el-switch
                                v-model="ruleForm.n_isValid"
                                active-color="#07AAF9"
                                inactive-color="#FF5F33"
                                inline-prompt
                                :active-text="$t('iPfonvtxVLm7knSyCsLBo')"
                                :inactive-text="$t('tzm8JwYsKnqKoNhheJlJx')"
                            />
                        </el-form-item>
                    </el-col>

                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item :label="$t('cymLlSzSGvDCuvZqXJgW')" :label-width="formLabelWidth">
                            <el-select 
                                filterable 
                                class="m-2" 
                                placeholder="" 
                                v-model="ruleForm.c_CheckResult" 
                                @change="changeState"
                            >
                                <el-option
                                    v-for="item in resultOption"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>

                    <el-col v-if="ruleForm.c_CheckResult === 'NG' && isShow" :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item :label="$t('3luGmFErt3lLyPpQgDFj')" prop="jobFile" :label-width="formLabelWidth">
                            <div class="upload-d">
                                <el-upload
                                    ref="uploadFileTwo"
                                    action="#"
                                    accept=".jpg,.png,.jpeg"
                                    multiple
                                    :show-file-list="false"
                                    :auto-upload='false'
                                    :on-change="insuranceChange"
                                    :before-upload="handleBeforeUpload"
                                    :on-remove="onRemove"
                                    style="width:100%"
                                >
                                    <el-button class="select-btn-s" v-if="showBtn"  type="primary" icon="ele-Plus" style="margin: 10px;">{{ $t('上 传') }}</el-button>
                                    <el-select
                                        v-if="isViewTwo"
                                        v-model="fileVal"
                                        multiple
                                        collapse-tags
                                        collapse-tags-tooltip
                                        :placeholder="$t('nthbPakxg2l96xNQhrywt')"
                                        style="width: 240px"
                                        @change="fileChange"
                                        @focus="fileFocus"
                                    >
                                        <el-option
                                            v-for="item in fileOptions"
                                            :key="item.uid"
                                            :label="item.name"
                                            :value="item.uid"
                                        />
                                    </el-select>
                                    <el-input v-else @click="uploadClick" readOnly slot="" :placeholder="$t('nthbPakxg2l96xNQhrywt')" />
                                </el-upload>
                            </div>
                        </el-form-item>
                    </el-col>

                    <template v-if="isShow">
                        <el-col v-if="ruleForm.c_CheckResult === 'NG'" :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                            <el-form-item :label="$t('lzDtAmbQGmFjXvWhfVq6T')" :label-width="formLabelWidth" prop="v_CheckNGContent">
                                <el-input type="textarea" v-model="ruleForm.v_CheckNGContent" :placeholder="$t('csOqgStv0hertG52Wbxgp')" clearable />
                            </el-form-item>
                        </el-col>

                        <el-col v-if="ruleForm.c_CheckResult === 'NG' && isShow" :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                            <el-form-item :label="$t('rIxr0IZu0V5CvKlfEYqBk')" :label-width="formLabelWidth" prop="d_AskCompliteDate">
                                <el-date-picker
                                    v-model="ruleForm.d_AskCompliteDate"
                                    type="datetime"
                                    value-format="YYYY-MM-DD HH:mm:ss"
                                    :placeholder="$t('xYKtSx361Hm1x9r3giOx')"
                                    popper-class="el-date-p"
                                >
                                </el-date-picker>
                            </el-form-item>
                        </el-col>

                        <el-col v-if="ruleForm.c_CheckResult === 'NG' && isShow" :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                            <el-form-item :label="$t('sT3qwPhxgfnL5y58ipVv1')" :label-width="formLabelWidth" prop="v_ExistsContent">
                                <el-input type="textarea" v-model="ruleForm.v_ExistsContent" :placeholder="$t('bzLj8dnd4dK5Bm8inb421')" clearable />
                            </el-form-item>
                        </el-col>

                        <el-col v-if="ruleForm.c_CheckResult === 'NG' && isShow" :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                            <el-form-item :label="$t('g350JxPlxfYj6IkYdvTmB')" prop="nGValue" :label-width="formLabelWidth">
                                <el-select 
                                    v-model="ruleForm.nGValue" 
                                    filterable 
                                    class="m-2" 
                                    :placeholder="$t('6Mtnnopp4UOtECuDjIu0m')" 
                                    value-key="id"
                                    @change="nGChange"
                                >
                                    <el-option
                                        v-for="item in nGOption"
                                        :key="item.id"
                                        :label="item.value"
                                        :value="item.id"
                                    />
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </template>

                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item :label-width="formLabelWidth" :label="$t('9RLaVEiJf1Z1Qv15o6Kll')">
                            <el-input type="textarea" v-model="ruleForm.v_Remake" :placeholder="$t('9RLaVEiJf1Z1Qv15o6Kll')" clearable />
                        </el-form-item>
                    </el-col>

                </el-row>

                <template v-if="isShowHazard">
                    <el-divider content-position="left">{{ $t('odQpuOypYmCIbyEj44TpZ') }}</el-divider>
                    <el-table
                        class="heightcss"
                        :data="hazardData" 
                        style="width: 100%"
                        v-loading="loadingXq"
                        element-loading-background="rgba(0, 0, 0, 0.5)"
                        border
                    >
                        <el-table-column min-width="200" prop="v_WorkType" show-overflow-tooltip :label="$t('9xM6FvTR_8nWq19wjfgx')"  align="center" />
                        <el-table-column min-width="200" prop="v_WorkExplain" show-overflow-tooltip :label="$t('f0faXf3TEmiEjagrud8d')"  align="center" />
                        <el-table-column min-width="200" prop="v_Shielding" show-overflow-tooltip :label="$t('fw78QmJeZpmsty3o1TeU')"  align="center" />
                        <el-table-column min-width="200" prop="v_Advice_Shielding" show-overflow-tooltip :label="$t('l4v70UyItNhFizQ4AInL6')"  align="center" />
                        <el-table-column min-width="200" show-overflow-tooltip :label="$t('3nAlWrFuulMoO3aQUqHFw')"  align="center">
                            <template #default="scope">
                                <div>
                                    <el-input @input="(val:any) => {inputValL(val , scope.$index)}" type="number" :max="9" :min="1" v-model="scope.row.f_Risk_Assessment_L" :placeholder="$t('3nAlWrFuulMoO3aQUqHFw')" clearable />
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column min-width="200" show-overflow-tooltip :label="$t('rzlqAtNgVas3PGjs9eFhn')"  align="center">
                            <template #default="scope">
                                <div>
                                    <el-input @input="(val:any) => {inputValE(val , scope.$index)}" type="number" :max="9" :min="1" v-model="scope.row.f_Risk_Assessment_E" :placeholder="$t('vzjxe4C0EfX2QfUhpBi')" clearable />
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column min-width="200" show-overflow-tooltip :label="$t('slyu5F1VcyleBwTfzDlu')"  align="center">
                            <template #default="scope">
                                <div>
                                    <el-input @input="(val:any) => {inputValC(val , scope.$index)}" type="number" :max="9" :min="1" v-model="scope.row.f_Risk_Assessment_C" :placeholder="$t('yti9hZsm0y2Motk9Ue4S')" clearable />
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column min-width="200" show-overflow-tooltip :label="$t('uzC1cOe6hQBnB9xRayozT')"  align="center">
                            <template #default="scope">
                                <div>
                                    <el-input readonly v-model="scope.row.f_Risk_Assessment_D" :placeholder="$t('hmmq3kjHcqEcKy3zaNcY9')" clearable />
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column min-width="200" prop="v_Dangerous_Level" show-overflow-tooltip :label="$t('gCP5cJhRMe0BnrLqRs')"  align="center" />
                        <el-table-column min-width="200" prop="v_Control_Level" show-overflow-tooltip :label="$t('7Lw5y52b0yczYwCbDguvq')"  align="center" />
                        <el-table-column min-width="200" prop="v_Control_Measures" show-overflow-tooltip :label="$t('xCeeB3WeM4ZkHhTh5btqG')"  align="center" />
                        <el-table-column min-width="200" prop="n_isValid" show-overflow-tooltip :label="$t('r1evDBkvvyoBmCg2EqMeX')"  align="center">
                            <template #default="scope">
                                <span v-if="scope.row.n_isValid === 1">{{ $t('ss3ajM0x7RzKcihXadp0h') }}</span>
                                <span v-if="scope.row.n_isValid === 2">{{ $t('3OlzfYe3W0LLu3oH76Sik') }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column :formatter="formatDate" prop="n_PushType" min-width="200" show-overflow-tooltip :label="$t('dHxlDhT9RRckG6mYRjgeQ')"  align="center" />
                        <el-table-column prop="v_Accient_TypeName" min-width="200" show-overflow-tooltip :label="$t('eQV4cIfknkpj60ezAzRr')"  align="center" />
                        <el-table-column prop="v_OrgName" min-width="200" show-overflow-tooltip :label="$t('cw6bUPoDlHdwNcW40my')"  align="center" />
                        <el-table-column prop="v_EmpName" min-width="200" show-overflow-tooltip :label="$t('y7I9J0Du746oyZTnse2kM')"  align="center" />
                        <el-table-column min-width="200" show-overflow-tooltip :label="$t('9RLaVEiJf1Z1Qv15o6Kll')"  align="center">
                            <template #default="scope">
                                <span v-if="scope.row.v_Remake"> {{ scope.row.v_Remake }} </span>
                                <span> - </span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="createdTime" min-width="200" show-overflow-tooltip :label="$t('xxAj6fsjvIsQrMdlNpolv')"  align="center" />
                        <el-table-column prop="createdUserName" min-width="200" show-overflow-tooltip :label="$t('v7AhfaNeGaFoPfZzgpFk')"  align="center" />
                        <el-table-column min-width="200" show-overflow-tooltip :label="$t('hMMqYalIdWhk0McqdxTg')"  align="center">
                            <template #default="scope">
                                <span v-if="scope.row.updatedTime"> {{ scope.row.updatedTime }} </span>
                                <span> - </span>
                            </template>
                        </el-table-column>
                        <el-table-column min-width="200" show-overflow-tooltip :label="$t('2Gu4SnAncIkNclplw6vNj')"  align="center">
                            <template #default="scope">
                                <span v-if="scope.row.updatedUserName"> {{ scope.row.updatedUserName }} </span>
                                <span> - </span>
                            </template>
                        </el-table-column>
                    </el-table>
                </template>

                <template v-if="isShowHandle">
                    <el-divider content-position="left">{{ $t('fV6bQYk1Mlv0i1cf61aLi') }}</el-divider>
                    <el-table
                        class="heightcss"
                        :data="rewardData" 
                        :key='refreshKey'
                        style="width: 100%"
                        v-loading="loading"
                        element-loading-background="rgba(0, 0, 0, 0.5)"
                        border
                    >
                        <el-table-column min-width="200" prop="orgName" :show-overflow-tooltip="true" :label="$t('8ua4Sp4niYurtPo7Th20')"  align="center" />
                        <el-table-column min-width="200" :show-overflow-tooltip="true" :label="$t('4M2xvh2QnhSfCyIzDlI0L')"  align="center">
                            <template #default="scope">
                                <div>
                                    <el-input @input="(val: any) => { rewardBlur(val , scope.row.indexId) }" v-model="scope.row.v_Reward" :placeholder="$t('4M2xvh2QnhSfCyIzDlI0L')" clearable />
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column min-width="200" :show-overflow-tooltip="true" :label="$t('pERgmNenpscuFClfXfoHx')"  align="center">
                            <template #default="scope">
                                <div>
                                    <el-input @input="(val: any) => { punishBlur(val , scope.row.indexId) }" v-model="scope.row.v_Punish" :placeholder="$t('2dHKk23lPXaJaZsAa4Vu1')" clearable />
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column min-width="200" :show-overflow-tooltip="true" :label="$t('sfwbsExMM3lGjDuN5zHf')"  align="center">
                            <template #default="scope">
                                <div>
                                    <el-switch
                                        v-model="scope.row.n_isValid"
                                        active-color="#13ce66"
                                        inactive-color="#ff4949"
                                        inline-prompt
                                        :active-text="$t('iPfonvtxVLm7knSyCsLBo')"
                                        :inactive-text="$t('tzm8JwYsKnqKoNhheJlJx')"
                                    />
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column min-width="200" :show-overflow-tooltip="true" :label="$t('mVbWgp3IFr_5Pxc1ZupP')"  align="center">
                            <template #default="scope">
                                <div>
                                    <el-select 
                                        filterable 
                                        class="m-2" 
                                        :placeholder="$t('qJ7ksw7Dspoat93E26WoP')" 
                                        v-model="scope.row.n_Type" 
                                        @change="(val:any) => {typeChange(val, scope.row.indexId)}"
                                    >
                                        <el-option
                                            v-for="item in typeOption"
                                            :key="item.id"
                                            :label="item.value"
                                            :value="item.id"
                                        />
                                    </el-select>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column min-width="200" :show-overflow-tooltip="true" :label="$t('rr09XnWJqvLmdTjHp')"  align="center">
                            <template #default="scope">
                                <div>
                                    <el-select 
                                        filterable 
                                        class="m-2" 
                                        :placeholder="$t('pzMrzIp3PqiIc3Va73pB')" 
                                        v-model="scope.row.n_Stardand" 
                                        @change="(val:any) => {standardChange(val, scope.row.indexId)}"
                                    >
                                        <el-option
                                            v-for="item in standardOption"
                                            :key="item.id"
                                            :label="item.value"
                                            :value="item.id"
                                        />
                                    </el-select>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column min-width="200" :show-overflow-tooltip="true" :label="$t('vAlE7MLemsQrKJqcOoI0V')"  align="center">
                            <template #default="scope">
                                <div>
                                    <el-select 
                                        filterable 
                                        class="m-2" 
                                        :placeholder="$t('c4Zg98enVqYj9yvmdn43g')" 
                                        v-model="scope.row.n_ResEmp" 
                                        @change="(val:any) => {resEmpChange(val, scope.row.indexId)}"
                                    >
                                        <el-option
                                            v-for="item in resEmpOption"
                                            :key="item.id"
                                            :label="item.name"
                                            :value="item.id"
                                        />
                                    </el-select>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column min-width="200" :show-overflow-tooltip="true" :label="$t('cNbYryin6Gyc2U3erwin')"  align="center">
                            <template #default="scope">
                                <div>
                                    <el-select 
                                        filterable 
                                        class="m-2" 
                                        :placeholder="$t('yzOQ5mDWdA4pGeLafxzB')" 
                                        v-model="scope.row.n_Measure"
                                        @change="(val:any) => {measureChange(val, scope.row.indexId)}" 
                                    >
                                        <el-option
                                            v-for="item in measureOption"
                                            :key="item.id"
                                            :label="item.value"
                                            :value="item.id"
                                        />
                                    </el-select>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column min-width="200" :show-overflow-tooltip="true" :label="$t('zctv01TFCs72lyzVrJdJ')"  align="center">
                            <template #default="scope">
                                <div>
                                    <el-select 
                                        filterable 
                                        class="m-2" 
                                        :placeholder="$t('sjVqIwzzqFowcu4HHul5')" 
                                        v-model="scope.row.n_Frequency" 
                                        @change="(val:any) => {frequencyChange(val, scope.row.indexId)}"
                                    >
                                        <el-option
                                            v-for="item in frequencyOption"
                                            :key="item.id"
                                            :label="item.value"
                                            :value="item.id"
                                        />
                                    </el-select>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column min-width="200" :show-overflow-tooltip="true" :label="$t('yzYLfcOEl8tpslWb9cttj')"  align="center">
                            <template #default="scope">
                                <div>
                                    <UploadFile
                                        :fileName="$t('zxGaloajaAo1yMttcFile')"
                                        :id="'file' + scope.row.indexId"
                                        :fileOptions="scope.row.file"
                                        @fileArr="(arr:any) => {fileArrFun(arr , scope.row.indexId)}"
                                    />
                                </div>
                                <!-- <div class="upload-d">
                                    <el-upload
                                        :ref = "( el:any ) => { setItemRef( el ) }"
                                        action="#"
                                        :multiple="false"
                                        :show-file-list="false"
                                        :auto-upload='false'
                                        class="upload-style"
                                        :on-change="( file:any, fileList:any ) => { empImageChange(file, fileList, scope.row.indexId) }"
                                        style="width:100%"
                                    >
                                        <el-input v-if="!scope.row.fileData.isView" readOnly slot="" placeholder="上传图片" />
                                        <el-input v-else v-model="scope.row.fileData.empImageVal" readOnly slot="" />
                                    </el-upload>
                                    <div class="upload-b">
                                        <el-tooltip effect="dark" content="移 除" placement="top">
                                            <el-icon @click="cancelDepClick(scope.row.indexId)" style="background: unset !important;cursor:pointer;">
                                                <Delete />
                                            </el-icon>
                                        </el-tooltip>
                                    </div>
                                </div> -->
                            </template>
                        </el-table-column>
                        <el-table-column min-width="300" :show-overflow-tooltip="true" :label="$t('orPmZf9puV0nzuHVmnPf')"  align="center">
                            <template #default="scope">
                                <div>
                                    <el-input type="textarea" @input="(val: any) => { resultBlur(val , scope.row.indexId) }" v-model="scope.row.v_Result" :placeholder="$t('dBhGaJyPHtt2gR6L1Z8S')" clearable />
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column min-width="300" :show-overflow-tooltip="true" :label="$t('9RLaVEiJf1Z1Qv15o6Kll')"  align="center">
                            <template #default="scope">
                                <div>
                                    <el-input type="textarea" @blur="(val: any) => { remarkBlur(val , scope.row.indexId) }" v-model="scope.row.v_Remark" :placeholder="$t('9RLaVEiJf1Z1Qv15o6Kll')" clearable />
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column min-width="160" :label="$t('liBmO8wb58NMw5HLu9Nf')" align="center" fixed="right">
                            <template #default="scope">
                                <div>
                                    <el-button @click="nodeClick(scope.row.indexId)" icon="ele-Plus" size="small" text type="primary"> {{ $t('w4dyKdalGlmq6BkxOjP7Q') }} </el-button>
                                    <el-button @click="deleteHandle(scope.row.indexId)" class="icon-e" icon="ele-Delete" size="small" text type="danger"> {{ $t('mkwlMbm3qr88f0XxV9Pje') }} </el-button>
                                </div>
                            </template>
                        </el-table-column>
                    </el-table>
                </template>
            </el-form>
            <template #footer>
                <el-button @click="cancelUseClick">{{ $t('yk_2HiWXbUkfQ7F6e3kXw') }}</el-button>
                <el-button type="primary" :disabled="repeatDis" @click="submitForm(ruleFormRef)">{{ $t('zdZCl09qrTjuPhYzWz7L') }}</el-button>
            </template>
        </el-dialog>
    </div>
</template>
<script lang="ts">
import { defineComponent, ref, reactive , computed , toRef , Ref , toRefs , toRaw , onMounted, watch } from 'vue'
import { FormInstance, FormRules , ElMessage, ElButton, ElCol, ElDatePicker, ElDialog, ElDivider, ElForm, ElFormItem, ElInput, ElOption, ElRadio, ElRow, ElSelect, ElTable, ElTableColumn, carouselEmits , ElMessageBox } from 'element-plus'
import { 
    SecurityCheckAdd , 
    ProviderGetList , 
    sysDictDataList , 
    sysOrgTree , 
    sysEmpSelector , 
    SecurityCheckUpdate ,
    projectitemSelector ,
    HazardGetHazardTree ,
    HazardGetHazardLevelList ,
    sysOrgGetParentOrgIdt ,
    AttendanceRecordGenerateId ,
    sysFileInfoMultipleUpload ,
    sysFileInfoMultipleUploads,
    sysFileInfoDelete ,
} from '/@/api/sms/sms';
import axios from 'axios';
import UploadFile from '../../components/upload-file.vue';
import useCurrentInstance from '/@/utils/hook/useCurrentInstance';

/*** 定义接口基础数据类型 */
interface formType {
    repeatDis: Boolean,
    n_ItemProjectId: String | Number,
    ruleForm: ruleFormType,
}
/*** form 表单数据类型 */
type ruleFormType = {
    n_Id?: Number, // 主键id
    nGFile: String, // 不良图片
    v_CheckNGContent: String, // 不良描述文字描述
    d_AskCompliteDate: String, // 要求完成时间
    v_ExistsContent: String, // 存在的主要问题
    
    n_ProjectId: Number, // 项目Id
    v_ProjectName: String, // 项目名称（用于显示）

    n_CheckType: Number, // 检查类别
    v_CheckTypeName: String, // 检查类别名称（用于显示）

    n_ThenCheckType: Number, // 后续巡检类别
    v_ThenCheckTypeName: String, // 后续巡检类别名称（用于显示）

    n_OrgId: Number | String, // 检查部门/班组
    v_TeamName: String, // 组织名称(用于显示)

    n_NGType: Number, // 不良描述分类
    nGValue: String, // 不良描述分类（用于显示）

    levelIds: any | [], // 危险源外键ID
    levelNodeIds?: any | [],


    n_ProviderRecordId: Number, // 供应商奖罚记录Id

    n_SecurityEmp: Number, // 安全员
    v_SecurityEmpName: String, // 安全员姓名（用于显示）


    c_CheckResult: String, // 检查结果 OK/NG
    d_CheckDate: String, // 检查日期
    v_Weather: String, // 天气情况
    v_WorkContent: String, // 工作内容

    n_isValid: Boolean, // 否启用 1启用/2禁用
    v_Remake: String, // 备注
}
export default defineComponent( {
    name: 'add-edit-site-inspection',
    components: { 
        UploadFile 
    },
    props: {
        isUseDialog:{
            type: Boolean,
            default: false,
        },
        repairInfo: {
            type: String,
            default: ''
        }
    },
    setup(props:any,ctx:any){
        const { proxy } = useCurrentInstance();
        const $t = proxy.$t;
        
        const titleCon = ref()
        const ruleFormRef:Ref = ref(null)

        const merchantOption = ref()
        const projectOption = ref()
        const checkOption = ref()
        const thenOption = ref()
        const treeData = ref()
        const nGOption = ref()
        const explainOption = ref()
        const securOption = ref()
        const checkRenOption = ref()    
        let baseUrl = import.meta.env.VITE_HOST_URL as any
        const service = axios.create({ baseURL: baseUrl, timeout: 5000 })
        const api1 = 'https://restapi.amap.com/v3/ip'
        const weatherApi = 'https://restapi.amap.com/v3/weather/weatherInfo'

        const isShow = ref(false)
        const typeOption:any = ref([])
        const standardOption:any = ref([])
        const measureOption:any = ref([])
        const frequencyOption:any = ref([])
        const resEmpOption: any = ref([]) // 责任人
        const hazardData:any = ref([]) // 危险源详情
        const loadingXq:any = ref(false)

        const rewardData:any = ref([])
        const loading = ref(false)
        const refreshKey = ref(false)
        
        // let itemRefs:any = []
        let orgId:any = ''
        let orgName:any = ''
        const isShowHandle = ref(false)
        const isShowHazard = ref(false)
        rewardData.value = [{
            n_ProvideId: orgId, // 供应商id
            orgName: orgName, // 供应商名称

            v_Reward: '', // 奖励
            v_Punish: '', // 惩罚
            n_isValid: true, // 是否启用
            n_Type: '', // 奖罚类型
            n_Stardand: '', // 奖罚标准
            n_ResEmp: '', // 奖罚管理责任人
            n_Measure: '', // 奖罚措施
            n_Frequency: '', // 奖罚时间频率
            v_Result: '', // 奖罚结果反馈
            file: [],
            n_FileId: 0,
            indexId: 0,
            fileData: {
                isView: false,
                empImageVal: '',
            },
            v_Remark: '-', // 备注
        }]

        // ===============多文件上传封装方法===========

        /***  fileArrFun 文件上传数据回传 */
        const fileArrFun = (arr:any , inx?: any) => {
            // console.log(arr,'arr')
            // console.log(inx,'inx')
            if(inx === 0 || inx){
                toRaw(rewardData.value)[inx].file = arr
            }
            fileInfoFun(arr)
        }
        /*** fileInfoFun 处理文件格式 */
        const fileInfoFun = (file: any) => {
            let fileArr:any = []
            if(file.length !== 0){
                file.map((i:any) => {
                    fileArr.push(i.raw)
                })
            }
            return fileArr
        }
        /*** uploadFileFuns 多文件上传无返回提示 */
        const uploadFileFuns = async (file: any , xhId: Number) => {
            let param:any = {}
            param.files = file
            param.sourceType = 'SMS'
            param.sourceId = xhId
            let res:any = await sysFileInfoMultipleUploads(param)
            if(res.success) return
        }
        // ===============多文件上传封装方法===========

        // =============== 多文件上传基础数据定义 =====
		const fileVal:any = ref([]) // 上传身份证下拉框model值
        const fileOptions:any = ref([])
        const showBtn = ref(false)
        const isViewTwo = ref(false)
        const uploadFileTwo:Ref = ref(null)
        let NGsnowflakeId:any = 0
		// =============== 多文件上传基础数据定义 =====

        // ================== 多文件上传事件 ==========

        const arrContrastFun = (arr1?:any , arr2?:any) => {
		    let newArr = []
		    if(arr1.length !== 0 && arr2.length !== 0){
		        for(let i = 0; i < arr1.length; i++){
		            for(let e = 0; e < arr2.length; e++){
		                if(arr1[i] === arr2[e].uid){
		                    newArr.push(arr2[e])
		                }
		            }
		        }
		    }
		    return newArr;
		}

        /*** fileChange select改变事件 */
        const fileChange:any = (val:any) => {
            uploadFileTwo.value.handleRemove((e:any) => { })
            if(val.length === 0){
                isViewTwo.value = false
                uploadFileTwo.value.clearFiles()
                fileVal.value = []
                fileOptions.value = []
            }
            if(val.length > 0){
                showBtn.value = true
            }else{
                showBtn.value = false
            }
            fileOptions.value = arrContrastFun(val , toRaw(fileOptions.value))
        }

        /*** uploadClick 触发上传组件获取雪花id */
        const uploadClick = async () => {
            if(props.repairInfo === ''){
                NGsnowflakeId = await getNeedId()
            }
        }

        /*** insuranceChange 不良文件改变事件 */
        const insuranceChange = (item:any) => {
            isViewTwo.value = true
            fileOptions.value.push(item)
            fileVal.value.push(item.uid)
            if(toRaw(fileOptions.value).length !== 0){
                showBtn.value = true
            }else{
                showBtn.value = false
            }
        }

        /*** uploadFileFun 文件上传函数 */
        const uploadFileFun = async(file:any) => {
            let param:any = {}
            param.files = file
            param.sourceType = 'SMS'
            param.sourceId = NGsnowflakeId
            let res:any = await sysFileInfoMultipleUpload(param)
            if(res.success) return
        }

        /*** uploadFileFunCs 文件上传函数 */
        const uploadFileFunCs = async(file:any , id: any) => {
            let filtArr:any = []
            file.map((i: any) => {
                filtArr.push(i.raw)
            })
            let param:any = {}
            param.files = filtArr
            param.sourceType = 'SMS'
            param.sourceId = id
            let res:any = await sysFileInfoMultipleUpload(param)
            if(res.success) return
        }

        /*** fileFocus select获取焦点的时候触发 */
        const fileFocus = () => {
            fileOptions.value = arrContrastFun(toRaw(fileVal.value) , toRaw(fileOptions.value))
        }

        const onRemove = (file:any,fileList:any) => {
		    let getFile = JSON.parse(JSON.stringify(fileList))
		    if(getFile.length === 0){
		        showBtn.value = false
		    }
		}

        /*** handleBeforeUpload 文件上传时的钩子函数 */
        const handleBeforeUpload = (file:any) => {
            // console.log(fileOptions.value,'文件上传时的钩子')
        }

        /*** getNeedId 获取雪花id */
        const getNeedId = async () => {
            let res:any = await AttendanceRecordGenerateId()
            let xhData = res.data
            if(props.repairInfo === ''){
                NGsnowflakeId = xhData
            }
            if(res.success) return xhData;
        }

        // ================== 多文件上传事件 ==========

        /*** formatDate 数据截取 */
        const formatDate = (row:any, column:any) => {
            let data = row[column.property]
            if(data <= 1){ return $t('7dvrp8KNteJ2KsyX53N') };
            if(data === 2){ return $t('0GdEpZhBB3RGlirtCm1U') };
            if(data === 3){ return $t('w3sd0wQwiYthGeopJcU4t') };
            if(data === 4){ return $t('eec8W28NIj_1hBweAkWs') };
            if(data === 5){ return $t('tuRoDlk7koL463Gf9SbzY') };

        }

        /*** changeState 检查结果改变事件 */
        const changeState = async(val: any) => {
            // console.log(val,'val')
            // console.log(toRaw(state.ruleForm).levelIds,'levelIds')
            if(toRaw(state.ruleForm).n_OrgId && toRaw(state.ruleForm).n_OrgId !==''){
                toRaw(rewardData.value)[0].n_ProvideId = orgId
                toRaw(rewardData.value)[0].orgName = orgName
                toRaw(rewardData.value)[0].n_FileId = await getNeedId()
            }else{
                state.ruleForm.c_CheckResult = ''
                ElMessage({
                    message: $t('s4MeUdQem1RVV28hkvY'),
                    type: 'warning',
                    duration: 1500
                })
                return
            }

            if(val === 'NG'){
                if(toRaw(state.ruleForm).levelIds.length !== 0){ 
                    isShowHandle.value = true
                }else{
                    isShowHandle.value = false
                    state.ruleForm.c_CheckResult = ''
                    ElMessage({
                        message: $t('gmgs6p0ufhcUc6cDp5Icq'),
                        type: 'warning',
                        duration: 1500
                    })  
                }
            }else{
                isShowHandle.value = true
            }
        }

        /*** setItemRef 动态ref */
        const setItemRef = (el:any) => {
            // if(el){ itemRefs.push(el) }
        }

        /*** nodeClick 新增 */
        const nodeClick = (val:any) => {
            loading.value = true
            // itemRefs = []
            let len = toRaw(rewardData.value).length - 1
            let rewardInputNum = toRaw(rewardData.value)[len]
            if(rewardInputNum.v_Reward === '' && rewardInputNum.v_Punish === ''){
                ElMessage({
                    message: $t('wmGgLp8qkhNXzeiE26Uq8') + toRaw(rewardData.value).length + $t('oriVfCoaN7H4HLsEdPdV'),
                    type: 'error',
                    duration: 2000
                })
                loading.value = false
                return
            };
            setTimeout(async () => {
                let setObj = {
                    n_ProvideId: orgId, // 供应商id
                    orgName: orgName, // 供应商名称

                    v_Reward: '', // 奖励
                    v_Punish: '', // 惩罚
                    n_isValid: true, // 是否启用
                    n_Type: '', // 奖罚类型
                    n_Stardand: '', // 奖罚标准
                    n_ResEmp: '', // 奖罚管理责任人
                    n_Measure: '', // 奖罚措施
                    n_Frequency: '', // 奖罚时间频率
                    v_Result: '', // 奖罚结果反馈
                    file: [],
                    n_FileId: await getNeedId(),
                    indexId: toRaw(rewardData.value).length,
                    fileData: {
                        isView: false,
                        empImageVal: '',
                    },
                    v_Remark: '-', // 备注
                }
                rewardData.value.push(setObj)
                refreshKey.value = !refreshKey.value
                loading.value = false
            },100)
        }

        /*** deleteHandle 删除 */
        const deleteHandle = (val:any) => {
            // console.log(val,'val')
            loading.value = true
            if(toRaw(rewardData.value).length === 1){
                ElMessage({
                    message: $t('w6lSn5xWDurtJ0Wo30Fm'),
                    type: 'error',
                    duration: 800,
                    onClose: () => {
                        loading.value = false
                    }
                })
            }else{
                // itemRefs[val].clearFiles()
                let setArr:any = toRaw(rewardData.value)
                setArr.splice(val,1)
                setArr.forEach((item:any,inx:any) => {
                    item.indexId = inx
                })
                ElMessage({
                    message: $t('z7Lu2v4We_2OgKzS7D9mX'),
                    type: 'success',
                    duration: 200,
                    onClose: () => {
                        refreshKey.value = !refreshKey.value
                        rewardData.value = setArr
                        // itemRefs.splice(val,1)
                        loading.value = false
                    }
                })
            }
        }

        /*** empImageChange 数据文件上传 */
        const empImageChange = (file:any, fileList:any, inx:any) => {
            let rewardInputVal = toRaw(rewardData.value)[inx]
            if (fileList.length > 1) {
                fileList.splice(0, 1); // 当上传文件大于1的时候替换，移除之前的文件（0是要删除数组的下标，1是要删除的数量）
            }
            rewardInputVal.fileData.isView = true
            rewardInputVal.fileData.empImageVal = file.name
            rewardInputVal.file = file.raw
        }
        /*** cancelDepClick 移除数据文件 */
        const cancelDepClick = (val:any) => {
            // console.log(val,'val')
            let rewardInputVal = toRaw(rewardData.value)[val]
            // console.log(rewardInputVal,'rewardInputVal')
            if(rewardInputVal.fileData.empImageVal === ''){
                ElMessage({
                    message: $t('93VguUt2xKl7hrhyTq3sD') + (val + 1) + $t('evQxiGy9lSct4DdpeaaHt'),
                    type: 'error',
                    duration: 1500
                })
            }else{
                ElMessage({
                    message: $t('0UcNx90XGonNwmu6kFak'),
                    type: 'success',
                    duration: 1000,
                    onClose: () => {
                        // itemRefs[val].clearFiles()
                        rewardInputVal.fileData.isView = false
                        rewardInputVal.fileData.empImageVal = ''
                    }
                })
            }
        }
        
        const treeRef:Ref = ref(null)

        /*** state 引用接口定义基础数据初始值 */
        const state = reactive < formType > ({
            repeatDis: false,
            n_ItemProjectId: '',
            ruleForm: {} as ruleFormType
        })

        /*** hazardChange 危险源改变事件 */
        const hazardChange = (val: any) => {
            // console.log(toRaw(val),'val')
            if(toRaw(val).length !== 0){
                isShowHazard.value = true
            }else{
                isShowHazard.value = false
            }
            hazardInfo(toRaw(val))
        }

        /*** hazardInfo 获取危险源详情数据 */
        const hazardInfo = async (idArr:any) => {
            loadingXq.value = true
            await HazardGetHazardLevelList({ Ids: idArr }).then((res:any) => {
                if(res.success){
                    // console.log(res.data,'data')
                    hazardData.value = res.data
                }
            })
            loadingXq.value = false
        }

        /*** 基础验证 rules */
        const rules = reactive < FormRules > ({
            /*** 放置验证 */

            // 不良图片
            nGFile: [
				{ required: true, message: $t('h2On71KpqQ8nWo8c0qFkn'), trigger: 'blur' },
			],
            // 不良文字描述
            v_CheckNGContent: [
				{ required: true, message: $t('fKRwabDc_9oIq4YcStYlB'), trigger: 'blur' },
			],
            // 要求完成时间
            d_AskCompliteDate: [
				{ required: true, message: $t('wFkRg6N34oncEzs2Gaj4h'), trigger: 'blur' },
			],
            // 存在主要问题
            v_ExistsContent: [
				{ required: true, message: $t('rtdWyBIbuoNrN3oHqas'), trigger: 'blur' },
			],
            // 检查日期
            d_CheckDate: [
				{ required: true, message: $t('qvcMbldwmeV5RiBd4Crrs'), trigger: 'change' },
			],
            // 天气
            v_Weather: [
				{ required: true, message: $t('234UZr23zSa64R431LYt0'), trigger: 'blur' },
			],
            // 工作内容
            v_WorkContent: [
				{ required: true, message: $t('pkZuDrlQWpMhvLXvGaVl'), trigger: 'blur' },
			],
            // 项目名称
            n_ProjectName: [
				{ required: true, message: $t('vsuJisJa9dQlSlfDs5XFu'), trigger: 'change' },
			],
            // 检查类别
            v_CheckTypeName: [
				{ required: true, message: $t('mHyj4nHsipCEnezJHhvEr'), trigger: 'change' },
			],
            // 后续巡检类别
            v_ThenCheckTypeName: [
				{ required: true, message: $t('ly8bQjlfyoFgP7n2XeeFb'), trigger: 'change' },
			],
            // 部门/班组
            n_OrgId: [
				{ required: true, message: $t('nSsGcEezCqGnckqsy'), trigger: 'change' },
			],
            // 不良描述分类
            nGValue: [
				{ required: true, message: $t('26qu3srRCbMmLr5KLrli'), trigger: 'change' },
			],
            // 危险源
            // levelIds: [
            //     { validator: hazardChange, required: true, trigger: 'change' },
			// ],
            levelIds: [
                { required: true, message: $t('zxGaloajaAo1yMttcTunx'), trigger: 'change' },
			],
            // 安全员
            v_SecurityEmpName: [
				{ required: true, message: $t('voFm5tk8rumSi1QgcrF0I'), trigger: 'change' },
			],
            // 项目名称
            v_ProjectName: [
                { required: true, message: $t('kJu7Trhi2W73OAVloSf'), trigger: 'change' },
            ],
        })

        /*** projectChange 项目下拉框改变事件 */
        const projectChange = (val:any) => {
            // console.log(val,'项目数据')
            state.ruleForm.n_ProjectId = val
            state.n_ItemProjectId = val
        }

        /*** checkChange 检查类别下拉框改变事件 */
        const checkChange = (val:any) => {
            // console.log(val,'检查类别')
            state.ruleForm.n_CheckType = val
        }

        /*** thenChange 后续巡检类别下拉框改变事件 */
        const thenChange = (val:any) => {
            // console.log(val,'后续巡检类别数据')
            state.ruleForm.n_ThenCheckType = val
        }

        /*** nGChange 不良描述分类下拉框改变事件 */
        const nGChange = (val:any) => {
            // console.log(val,'不良描述分类数据')
            state.ruleForm.n_NGType = val
        }

        /*** securChange 安全员下拉框改变事件 */
        const securChange = (val:any) => {
            // console.log(val,'安全员数据')
            state.ruleForm.n_SecurityEmp = val
        }

        /*** checkRenChange 检查人下拉框改变事件 */
        const checkRenChange = (val:any) => {
            // console.log(val,'检查人数据')
        }

        /*** orgChange 部门/班组下拉框改变事件 */
        const orgChange = (val:any) => {
            let getVal = toRaw(treeRef.value.getCurrentNode())
            state.ruleForm.n_OrgId = val
            getYsFun(val)
            getPersonnelFun(val)
            console.log(getVal.title,'getVal')
            rewardData.value.map((i:any) => {
                i.orgName = getVal.title
            })
            // rewardData.value = [{
            // n_ProvideId: orgId, // 供应商id
            // orgName: orgName, // 供应商名称
        }

        /*** getPersonnelFun 根据部门/班组获取员工数据 */
        const getPersonnelFun = async (id:any) => {
            let res:any = await sysEmpSelector({ N_OrgId: id })
            if(res.success) resEmpOption.value = res.data;
        }

        /*** getYsFun 获取第一级友商数据 */
        const getYsFun = async(num: any) => {
            let res:any = await sysOrgGetParentOrgIdt( { id: num } )
            // console.log(res,'res')
            if(res.success){
                orgId = res.data.orgId
                orgName = res.data.orgName
            } 
        }

        /*** handleClose 关闭按钮点击事件 */
        const handleClose = () => {
            cancelUseClick()
        }

        /*** cancelUseClick 取消事件 */
        const cancelUseClick = () => {
            cleanFile()
            ctx.emit('cancelUseClick')
        }

        /*** submitForm 提交事件 */
        const submitForm = (formEl: FormInstance | undefined) => {
            if(!formEl) return
            formEl.validate( async (valid) => { 
                if(valid){
                    // state.repeatDis = true
                    let getData:any = toRaw(state.ruleForm)
                    let param:any = {}
                    let valObj:any = {}
                    getData.n_isValid ? param.n_isValid = 1 : param.n_isValid = 2
                    const {
                        v_ProjectName , 
                        v_CheckTypeName ,
                        v_ThenCheckTypeName , 
                        nGValue , 
                        v_TeamName ,
                        levelIds ,
                        levelNodeIds ,
                        v_SecurityEmpName , 
                        nGFile ,
                        ...getArr} = getData
                    valObj = {...getArr,...param}
                    let getNeedArr:any = []
                    // 供应商奖罚处理
                    if(getData.c_CheckResult !== ''){
                        toRaw(rewardData.value).map((i:any) => {
                            delete i.fileData;
                            delete i.indexId;
                            i.n_isValid ? i.n_isValid = 1 : i.n_isValid = 2;
                            
                            if(i.n_Type === '') i.n_Type = 0; // 奖罚类型
                            if(i.n_Stardand === '') i.n_Stardand = 0; // 奖罚标准
                            if(i.n_ResEmp === '') i.n_ResEmp = 0; // 奖罚管理责任人
                            if(i.n_Measure === '') i.n_Measure = 0; // 奖罚措施
                            if(i.n_Frequency === '') i.n_Frequency = 0; // 奖罚时间频率
                            if(i.v_Result === '') i.v_Result = 0; // 奖罚结果反馈

                            getNeedArr.push(i);
                        })
                    }
                    // 危险源详情
                    if(toRaw(hazardData.value).length === 0){
                        // valObj.HazardLevelDetail = []
                        valObj.hazardLevelDetailStr = ''
                    }else{
                        // valObj.HazardLevelDetail = toRaw(hazardData.value)
                        valObj.hazardLevelDetailStr = JSON.stringify(toRaw(hazardData.value))
                    }
                    // 多文件上传
                    let fileArr:any = []
                    if(toRaw(fileOptions.value).length !== 0){
                        toRaw(fileOptions.value).map((i:any) => {
                            fileArr.push(i.raw)
                        })
                    }
                    if(fileArr.length !== 0){ 
                        if(props.repairInfo === ''){
                            uploadFileFuns(fileArr,NGsnowflakeId) 
                        }else{
                            uploadFileFuns(fileArr,getData.n_NgImage) 
                        }
                        
                    }
                    // 要求完成时间
                    if(!getData.d_AskCompliteDate || getData.d_AskCompliteDate === ''){
                        valObj.d_AskCompliteDate = $t('utiIUzqSzcKy0QiDc49n')
                    }
                    
                    console.log(getNeedArr,'getNeedArr12')
                    if(getNeedArr.length !== 0){
                        getNeedArr.map((item:any) => {
                            if(item.file && item.file.length !== 0){
                                item.file.map((i:any) => {
                                    uploadFileFuns(i.raw, item.n_FileId)
                                })
                            } 
                            delete item.file
                        }) 
                        valObj.addRewardStr = JSON.stringify(getNeedArr) 
                    }else{
                        valObj.addRewardStr = ''
                    }
                    // console.log(valObj,'valObj')
                    if(props.repairInfo === ''){
                        valObj.n_NgImage = NGsnowflakeId
                        let res:any = await SecurityCheckAdd(valObj)
                        if(res.success){
                            ctx.emit('controlUseClick','success')
                            ctx.emit('updateData')
                            cleanFile()
                        }
                    }else{
                        let res:any = await SecurityCheckUpdate(valObj)
                        if(res.success){
                            ctx.emit('controlUseClick','success')
                            ctx.emit('updateData')
                            cleanFile()
                        }
                    }
                }else{
                    console.log('error submit!')
					return false
                }
            })
        }

        /*** clean 清空数据 */
        const clean = () => {
            ruleFormRef.value.resetFields()
        }
        
        /*** cleanFile 清空文件数据 */
        const cleanFile = () => {
            if(uploadFileTwo.value){ 
                uploadFileTwo.value.clearFiles()
                fileOptions.value = []
                fileVal.value = []
            }
            rewardData.value = [{
                n_ProvideId: '', // 供应商id
                orgName: '', // 供应商名称

                v_Reward: '', // 奖励
                v_Punish: '', // 惩罚
                n_isValid: true, // 是否启用
                n_Type: '', // 奖罚类型
                n_Stardand: '', // 奖罚标准
                n_ResEmp: '', // 奖罚管理责任人
                n_Measure: '', // 奖罚措施
                n_Frequency: '', // 奖罚时间频率
                v_Result: '', // 奖罚结果反馈
                file: [], // 文件
                n_FileId: 0,
                indexId: 0,
                fileData: {
                    isView: false,
                    empImageVal: '',
                },
                v_Remark: '-', // 备注
            }]
            loading.value = false;
            // itemRefs = [];
            // if(itemRefs.length > 0){
            //     itemRefs.map((i:any) => {
            //         i.clearFiles()
            //     })
            // };
        }

        /*** 监听isUseDialog的变化 */
        watch(() => props.isUseDialog,(newVal) => {
            if(newVal){
                /*** ====状态重置==== */
                state.repeatDis = false
                state.n_ItemProjectId = ''
                orgId = ''
                orgName = ''
                isShowHandle.value = false
                isShowHazard.value = false

                // 多文件上传状态重置
                showBtn.value = false
                isViewTwo.value = false
                // 多文件上传状态重置

                /*** ====状态重置==== */
                getGdDataFun()
                GetInfo()
                if(props.repairInfo !== ''){
                    titleCon.value = $t('qdjaUu5q3JYq0bnq8l')
                    let setPara:any = {}
                    let getData = JSON.parse(props.repairInfo)
					console.log(getData,'getData')
                    hazarFun(getData.n_Id)
                    getData.n_isValid === 1 ? setPara.n_isValid = true : setPara.n_isValid = false
                    // getData.levelIds = [['416904778297413', '417611386613829']]
                    state.n_ItemProjectId = getData.n_ProjectId
                    orgId = getData.n_OrgId
                    orgName = getData.v_TeamName
                    if(getData.d_CheckDate === $t('utiIUzqSzcKy0QiDc49n')){
                        getData.d_CheckDate = ''
                    }
                    if(getData.c_CheckResult === ''){
                        isShow.value = true 
                    }else{
                        isShow.value = false
                    }
                    if(getData.levelNodeIds && getData.levelNodeIds.length !== 0){
                        hazardInfo(getData.levelNodeIds)
                        isShowHazard.value = true
                    }
                    const {
                        n_isValid , 
                        tenantId , 
                        isDeleted , 
                        updatedTime , 
                        updatedUserId , 
                        updatedUserName ,
                        createdTime ,
                        createdUserId ,
                        createdUserName ,
                        ...setData} = getData
                    state.ruleForm = { ...setPara , ...setData }
                    // console.log(getData,'getData')
                    merchantFun(getData.n_ProviderId)
                    getPersonnelFun(getData.n_OrgId)
                }else{
                    merchantFun()
                    hazarFun(0)
                    titleCon.value = $t('kfR7oKqGr0sNpRoAhHcM')
                    isShow.value = true
                    state.ruleForm.nGFile = '' // 不良图片
                    state.ruleForm.v_CheckNGContent = '' // 不良描述文字描述

                    state.ruleForm.n_NGType = 0 // 不良描述分类
                    state.ruleForm.nGValue = '' // 不良描述分类（用于显示）

                    state.ruleForm.d_AskCompliteDate = '' // 要求完成时间
                    state.ruleForm.v_ExistsContent = '' // 存在的主要问题

                    
                    state.ruleForm.n_ProjectId = 0 // 项目Id
                    state.ruleForm.v_ProjectName = '', // 项目名称

                    state.ruleForm.n_CheckType = 0 // 检查类别
                    state.ruleForm.v_CheckTypeName = '' // 检查类别名称（用于显示）

                    state.ruleForm.n_ThenCheckType = 0 // 后续巡检类别
                    state.ruleForm.v_ThenCheckTypeName = '' // 后续巡检类别（用于显示）

                    state.ruleForm.n_OrgId = '' // 检查部门/班组
                    state.ruleForm.v_TeamName = '' // 组织名称用于显示


                    state.ruleForm.c_CheckResult = '' // 检查结果 OK/NG
                    state.ruleForm.d_CheckDate = '' // 检查日期

                    state.ruleForm.n_SecurityEmp = 0 // 安全员
                    state.ruleForm.v_SecurityEmpName = '' // 安全员（用于显示）

                    state.ruleForm.levelIds = [] // 危险源外键ID

                    state.ruleForm.v_Weather = '' // 天气情况
                    state.ruleForm.n_ProviderRecordId = 0 // 供应商奖罚记录Id
                    state.ruleForm.v_WorkContent = '' // 工作内容
                    state.ruleForm.n_isValid = true // 否启用 1启用/2禁用
                    state.ruleForm.v_Remake = '' // 备注
                    getNeedId()
                }
            }
        })

        /*** isUseDialog 响应弹窗的关闭  */
        const isUseDialog = computed(() => {
            return props.isUseDialog
        })

        /*** merchantFun 供应商管理获取数据 */
        const merchantFun = async(n?:any) => {
            // 供应商数据下拉框
            let param:any = {}
            if(n){
                param.n_Id = n
            }
            let res:any = await ProviderGetList(param)
            if(res.success){
                // console.log(res.data,'供应商数据')
                merchantOption.value = res.data
                
            }
        }

        /*** GetInfo 获取所有信息 */
        const GetInfo = async () => {

            // 检查类别
            let checkRes:any = await sysDictDataList({ typeCode: 'check_type' })

            // 不良类型
            let securRes:any = await sysDictDataList({ typeCode: 'securitybad_type' })

            // 组织结构列表
            let orgRes:any = await sysOrgTree( { type: 2 } )

            // 人员信息
            let useRes:any = await sysEmpSelector()
            
            // 项目列表
            let projectRes:any = await projectitemSelector()
            
            if(checkRes.success){
                // console.log(checkRes.data,'检查类别数据')
                checkOption.value = checkRes.data
                thenOption.value = checkRes.data
            }
            if(orgRes.success){
                // console.log(orgRes,'组织机构数据')
                treeData.value = orgRes.data
            }
            if(securRes.success){
                // console.log(securRes,'不良类型数据')
                nGOption.value = securRes.data
            }
            if(useRes.success){
                // console.log(useRes,'人员信息')
                securOption.value = useRes.data
                checkRenOption.value = useRes.data
            }
            if(projectRes.success){
                // console.log(projectRes.data,'项目列表数据')
                projectOption.value = projectRes.data
            }

            /*** 
             * 备注: 字典类型Code（奖罚类型 provider_reward_punish/奖罚标准 stardand/奖罚措施 measure/奖罚时间频率 frequency）
             */
            let paramObj:any = {}
            let paramVal = ['provider_reward_punish','stardand','measure','frequency']
            for(let i = 0; i < paramVal.length; i++){
                paramObj.TypeCode = paramVal[i]
                let res = await sysDictDataList(paramObj)
                if(i === 0){ typeOption.value = res.data; }
                if(i === 1){ standardOption.value = res.data; }
                if(i === 2){ measureOption.value = res.data; }
                if(i === 3){ frequencyOption.value = res.data; }
            }
        }
        const hazarFun = async(num: Number) => {
            // 危险源
            let hazarRes:any = await HazardGetHazardTree({ n_TaskId: num })
            if(hazarRes.success){
                explainOption.value = hazarRes.data
				console.log(hazarRes.data,'hazarRes.data')
            }
        }

        onMounted(() => {
            
        })

        /*** getGdDataFun 获取高德数据 */
        const getGdDataFun = () => {
            service.get(api1,{
                params: {
                    key: '7e78624fc947972f3ea7028dd93ed2ea'
                }
            }).then((res:any) => {
                if(res.status === 200 && res.data.status === '1'){
                    service.get(weatherApi,{
                        params: {
                            city: res.data.city,
                            key: '7e78624fc947972f3ea7028dd93ed2ea',
                            extensions: 'base',
                        }
                    }).then((res:any) => {
                        if(res.status === 200 && res.data.status === '1'){
                            state.ruleForm.v_Weather = res.data.lives[0].weather
                        }else{
                            ElMessage({
                                type: 'error',
                                message: $t('aHjSnWy2nAcEt5Dvakw2v')
                            })
                        }
                    }).catch((error:any) => {
                        return
                    })
                }else{
                    ElMessage({
                        type: 'error',
                        message: $t('gTQoEn7PSKfgv59U4v1'),
                    })
                }
            }).catch((error:any) => {
                return
            })
        }

        /*** merchantChange 供应商改变事件 */
        const merchantChange = (val:any , inx:any) => {
            toRaw(rewardData.value)[inx].n_ProvideId = val
        }
        /*** rewardBlur 奖励失去焦点事件 */
        const rewardBlur = (val: any , inx: any) => {
            if(val !== ''){
                let valInfo = val.split(/[\t\r\f\n\s]*/g).join('') // 去除空格
                if(toRaw(rewardData.value)[inx].v_Punish === ''){
                    toRaw(rewardData.value)[inx].v_Reward = valInfo
                }else{
                    toRaw(rewardData.value)[inx].v_Reward = ''
                    ElMessage({
                        type: 'warning',
                        message: $t('cPbDXrdXk7Gd7Yvhl5Su1'),
                        duration: 1500
                    })
                }
            }
        }
        /*** punishBlur 处罚失去焦点事件 */
        const punishBlur = (val: any , inx: any) => {
            if(val !== ''){
                let valInfo = val.split(/[\t\r\f\n\s]*/g).join('') // 去除空格
                if(toRaw(rewardData.value)[inx].v_Reward === ''){
                    toRaw(rewardData.value)[inx].v_Punish = valInfo
                }else{
                    toRaw(rewardData.value)[inx].v_Punish = ''
                    ElMessage({
                        type: 'warning',
                        message: $t('l8C6Bx6CPUfUyTQhbhpQ'),
                        duration: 1500
                    })
                }
            }
        }
        /*** resultBlur 奖罚结果反馈失去焦点事件 */
        const resultBlur = (val: any , inx: any) => {
            if(val !== ''){
                let valInfo = val.split(/[\t\r\f\n\s]*/g).join('') // 去除空格
                toRaw(rewardData.value)[inx].v_Result = valInfo
            }
        }
        /*** remarkBlur 备注失去焦点事件 */
        const remarkBlur = (val: any , inx: any) => {
            if(val !== ''){
                let valInfo = val.split(/[\t\r\f\n\s]*/g).join('') // 去除空格
                toRaw(rewardData.value)[inx].v_Remark = valInfo
            }
        }
        /*** typeChange 奖罚类型改变事件 */
        const typeChange = (val: any, inx: any) => {
            toRaw(rewardData.value)[inx].n_Type = val
        }
        /*** standardChange 奖罚标准改变事件 */
        const standardChange = (val: any, inx: any) => {
            toRaw(rewardData.value)[inx].n_Stardand = val
        }
        /*** resEmpChange 奖罚管理责任人改变事件 */
        const resEmpChange = (val: any, inx: any) => {
            toRaw(rewardData.value)[inx].n_ResEmp = val
        }
        /*** measureChange 奖罚措施改变事件 */
        const measureChange = (val: any, inx: any) => {
            toRaw(rewardData.value)[inx].n_Measure = val
        }
        /*** frequencyChange 奖罚事件频率改变事件 */
        const frequencyChange = (val: any, inx: any) => {
            toRaw(rewardData.value)[inx].n_Frequency = val
        }

        /*** dangerLvFun 危险等级数据封装 */
        const dangerLvFun = (num:any) => {
            if (num >= 320)
                return $t('l1qAm7VsyKwVPeqIiKXmQ');
            else if (num >= 160 && num < 320)
                return $t('q4_8Ni0zYdshstVmk6vE8');
            else if (num >= 70 && num < 160)
                return $t('mH7IzD7A82j5cXrAxUl');
            else if (num >= 20 && num < 70)
                return $t('yn5hUhfYrU01jCrAlLlKc');
            else if (num < 20)
                return $t('bImoHC7OtqKwZhTi0xxL');
        }

        /*** inputValL 风险评估L值获取 */
        const inputValL = (val:any , inx:any) => {
            let L = 0
            if(val < 1){
                L = 1
            }else if(val > 9){
                L = 9
            }else{
                L = val
            }
            let E = toRaw(hazardData.value)[inx].f_Risk_Assessment_E
            let C = toRaw(hazardData.value)[inx].f_Risk_Assessment_C
            let D = Number(L) * Number(E) * Number(C)
            toRaw(hazardData.value)[inx].f_Risk_Assessment_L = Number(L)
            toRaw(hazardData.value)[inx].f_Risk_Assessment_D = D
            toRaw(hazardData.value)[inx].v_Dangerous_Level = dangerLvFun(D)
        }

        /*** inputValE 风险评估E值获取 */
        const inputValE = (val:any , inx:any) => {
            let E = 0
            if(val < 1){
                E = 1
            }else if(val > 9){
                E = 9
            }else{
                E = val
            }
            let L = toRaw(hazardData.value)[inx].f_Risk_Assessment_L
            let C = toRaw(hazardData.value)[inx].f_Risk_Assessment_C
            let D = Number(L) * Number(E) * Number(C)
            toRaw(hazardData.value)[inx].f_Risk_Assessment_E = Number(E)
            toRaw(hazardData.value)[inx].f_Risk_Assessment_D = D
            toRaw(hazardData.value)[inx].v_Dangerous_Level = dangerLvFun(D)
        }

        /*** inputValC 风险评估E值获取 */
        const inputValC = (val:any , inx:any) => {
            let C = 0
            if(val < 1){
                C = 1
            }else if(val > 9){
                C = 9
            }else{
                C = val
            }
            let L = toRaw(hazardData.value)[inx].f_Risk_Assessment_L
            let E = toRaw(hazardData.value)[inx].f_Risk_Assessment_E
            let D = Number(L) * Number(E) * Number(C)
            toRaw(hazardData.value)[inx].f_Risk_Assessment_C = Number(C)
            toRaw(hazardData.value)[inx].f_Risk_Assessment_D = D
            toRaw(hazardData.value)[inx].v_Dangerous_Level = dangerLvFun(D)
        }

        return {
            handleClose,
            submitForm,
            cancelUseClick,
            clean,
            ruleFormRef,
            titleCon,
            ...toRefs(state),
            isUseDialog,
            rules,
            formLabelWidth: '120px',
            merchantOption,

            projectChange,
            projectOption,

            checkChange,
            checkOption,

            thenChange,
            thenOption,

            treeData,
            treeProps: {label: 'title' , children: 'children'},
            orgChange,

            nGChange,
            nGOption,
            
            hazardChange,
            explainOption,

            securChange,
            securOption,

            checkRenChange,
            checkRenOption,

            treeRef,

            resultOption: [
                {label: 'OK', value: 'OK'},
                {label: 'NG', value: 'NG'},
            ], 

            rectiOption: [
                { label: $t('gsQNjjKc3Gdm5d9qiwHXk'), value: 1 },
                { label: $t('b5krNrA5QBz0shYNj25'), value: 2 },
                { label: $t('uKt4PrCmupaNhgk8hhAo'), value: 0 },
            ],
            
            isShow,
            typeOption,
            standardOption,
            measureOption,
            frequencyOption,
            resEmpOption,
            rewardData,
            refreshKey,

            nodeClick,
            deleteHandle,
            empImageChange,
            cancelDepClick,

            setItemRef,
            loading,
            changeState,
            merchantChange, // 供应商改变事件
            rewardBlur, // 奖励失去焦点事件
            punishBlur, // 处罚失去焦点事件
            typeChange, // 奖罚类型改变事件
            standardChange, // 奖罚标准改变事件
            resEmpChange, // 奖罚管理责任人改变事件
            measureChange, // 奖罚措施改变事件
            frequencyChange, // 奖罚事件频率改变事件
            resultBlur, // 奖罚结果反馈失去焦点事件
            remarkBlur, // 备注失去焦点事件
            checkProps: {
                multiple: true,
                checkStrictly: false,
                emitPath: false,
            },
            hazardData,
            loadingXq,
            formatDate,
            inputValL,
            inputValE,
            inputValC,
            isShowHandle,
            isShowHazard,

            // ==========多文件上传====
            insuranceChange,
            onRemove,
            showBtn,
            isViewTwo,
            fileVal,
            fileChange,
            fileFocus,
            fileOptions,
            uploadFileTwo,
            handleBeforeUpload,
            // ==========多文件上传====
            uploadClick,
            fileArrFun,
        }
    },
} )
</script>
<style scoped lang="scss">
    :deep(.el-select){
        width: 100%!important;
    }
    :deep(.el-input){
        width: 100%!important;
    }
    :deep(.el-upload){
        width: 100%!important;
    }
    // :deep(.el-divider__text){
    //     color: #303133!important;
    //     font-weight: bold!important;
    // }
    :deep(.el-cascader){
        width: 100%!important;
    }
    // 文件上传样式
    .upload-d{
        position: relative;
        width: 100%;
        :deep(.el-upload){
            width: 100%;
            // position: absolute;
            // top: 0;
            // left: 0;
        }
        .select-btn-s{
            position: absolute;
            top: 2px;
            right: 1px;
            z-index: 3;
            margin: 0!important;
            border: none!important;
            background: rgba(255,255,255,1)!important;
            color: #0052D9!important;
            height: 28px;
        }
        .select-btn-s:active{
            color: #0052D9!important;
        }
        .select-btn-s:hover{
            color: #0052D9!important;
        }
        .upload-b{
            display: flex;
            align-items: center;
            position: absolute;
            top: 8px;
            right: 10px;
            line-height: initial;
            background: unset !important;
            :deep(a){
                background: unset !important;
                margin-right: 10px;
            }
            :deep(span){
                background: unset !important;
            }
        }
    }
</style>